export default {
  // 为当前模块开启命名空间
  namespaced: true,
  state: () => ({
      // 购物车的数组，用来存储购物车中每个商品的信息对象
      // 每个商品的信息对象，都包含如下 6 个属性：
      // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
      cart: JSON.parse(uni.getStorageSync('cart')) || [],
    }),
    mutations: {
      addToCart(state, goods) {
        const findResult = state.cart.find((item) => item.goods_id === goods.goods_id)//返回结果为满足条件的第一个x，都不满足则返回undefined
        if (!findResult) {
          state.cart.push(goods)
        } else {
          findResult.goods_count++
        }
        
        // 通过 commit 方法，调用 m_cart 命名空间下的 saveToStorage 方法
        this.commit('m_cart/saveToStorage')
      },
      saveToStorage(state) {
        uni.setStorageSync('cart', JSON.stringify(state.cart))
      },
      updateGoodsState(state, goods) {
        // 根据 goods_id 查询购物车中对应商品的信息对象
        const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
      
        // 有对应的商品信息对象
        if (findResult) {
          // 更新对应商品的勾选状态
          findResult.goods_state = goods.goods_state
          // 持久化存储到本地
          this.commit('m_cart/saveToStorage')
        }
        // console.log(state.cart)
      },
      updateGoodsCount(state, goods) {
        const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
        if (findResult) {
          findResult.goods_count = goods.goods_count
          // console.log('yes')
          this.commit('m_cart/saveToStorage')
        }
      },
      removeGoodsById(state, goods_id) {
        state.cart = state.cart.filter(item => item.goods_id !== goods_id)
        this.commit('m_cart/saveToStorage')
      },
      updateAllGoodsState(state, newState) {
        state.cart.forEach(item => item.goods_state = newState)
        this.commit('m_cart/saveToStorage')
      }
    },
    getters: {
      total(state) {
        // let c = 0
        // state.cart.forEach(item => {
        //   c += item.goods_count
        // })
        // return c
        return state.cart.reduce((total, item) => total += item.goods_count, 0)
      },
      checkedCount(state) {
        return state.cart.filter(item => item.goods_state).reduce((checkedCount, item) => checkedCount += item.goods_count, 0)
      },
      checkedGoodsAmount(state) {
        return state.cart.filter(item => item.goods_state)
                         .reduce((amount, item) => amount += item.goods_count * item.goods_price, 0)
                         .toFixed(2)
      }
    }
}